package net.gdface.service.search;

import java.net.URI;
import java.net.URISyntaxException;

import net.gdface.worker.QueueManager;

import org.apache.http.client.utils.URIBuilder;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SearchSimilarImgImplBaidu extends SearchSimilarImgImpl implements SearchSimilarImg {
	private static final Logger logger = LoggerFactory.getLogger(SearchSimilarImgImplBaidu.class);
	private static final URI SE_SIMILAR_PAGE;
	private static final URI SE_SIMILAR_URI_FOR_JSON;
	private static final int PAGE_SIZE = 120;
	static {
		try {
			SE_SIMILAR_PAGE = new URI("http://shitu.baidu.com/n/pc_search");
			SE_SIMILAR_URI_FOR_JSON =	new URIBuilder("http://shitu.baidu.com/n/similar")
					.setParameter("pn", "0")
					.setParameter("rn", Integer.toString(PAGE_SIZE)).setParameter("sort", "").build();
		} catch (URISyntaxException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public SearchSimilarImgImplBaidu(QueueManager<RemoteImageWOC> queueManager) {
		super(queueManager);
	}

	@Override
	protected URI createHTMLUri() {
		try {
			return new URIBuilder(SE_SIMILAR_PAGE).setParameter("queryImageUrl", this.srcImg.toString()).build();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected String getArrayKey() {
		return "data";
	}

	@Override
	protected URI nextPage(URI lastPage, int page) {
		try {
			URI target = null == lastPage ? new URIBuilder(SE_SIMILAR_URI_FOR_JSON).setParameter("queryImageUrl",
					srcImg.toString()).build() : lastPage;
			return new URIBuilder(target).setParameter("pn", Integer.toString(page)).build();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected int getTotal() {
		try {
			int total=this.jsonResp.getJSONObject("extra").getInt("totalNum");
			if(total>totalImage)
				totalImage=total;
			return totalImage;
		} catch (JSONException e) {
			logger.error("CAN'T GET 'totalNum' on 'extra' from JSON {}", e.toString());
			return totalImage!=Integer.MAX_VALUE?totalImage:0;
		}
	}

	@Override
	protected int getPageSize() {
		try {
			return this.jsonResp.getJSONObject("extra").getInt("rn");
		} catch (JSONException e) {
			logger.error("CAN'T GET 'rn' on 'extra' from JSON {}", e.toString());
			return PAGE_SIZE;
		}
	}

	@Override
	protected ImgJsonDecoder getImgJsonDecoder() {
		return ImgJsonDecoder.BAIDU;
	}

	@Override
	protected boolean isValidResp() throws JSONException {
		try {
			int errorno = this.jsonResp.getInt("errno");
			if(errorno!=0){
				logger.info("errorno:[{}] {} {}", errorno,this.jsonResp.getString("errmsg"),srcImg.toString());
			}
			return errorno==0;
		} catch (JSONException e) {
			logger.error("CAN'T GET 'errno' on 'extra' from JSON {}", e.toString());
			throw e;
		}
	}
	@Override
	protected boolean isContinue() throws JSONException {
		try {
			switch (this.jsonResp.getInt("errno")) {
			case -4:
				return false;
			default:
				return true;
			}
		} catch (JSONException e) {
			logger.error("CAN'T GET 'errno' on 'extra' from JSON {}", e.toString());
			throw e;
		}
	}

	@Override
	protected boolean isLast() {
		return startIndex >= getTotal();
	}
	
}